/*
 * @Author: xzy 1453077527@qq.com
 * @Date: 2025-08-19 17:10:11
 * @LastEditors: xzy 1453077527@qq.com
 * @LastEditTime: 2025-08-19 17:10:43
 * @Description:
 */
package com.xtedu.examproject.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter("/*")
public class EncodingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 设置请求编码
        req.setCharacterEncoding("UTF-8");

        // 设置响应编码
        resp.setCharacterEncoding("UTF-8");

        // 不对静态资源设置Content-Type
        String requestURI = req.getRequestURI();
        if (!isStaticResource(requestURI)) {
            resp.setContentType("text/html;charset=UTF-8");
        }

        chain.doFilter(request, response);
    }

    private boolean isStaticResource(String uri) {
        return uri.matches(".*\\.(css|js|png|jpg|jpeg|gif|ico|woff|woff2|ttf|svg)$");
    }
}
